<?php
class SearchController extends AppController {
	var $name = 'Search';
	var $uses = array();
	var $view = 'Theme';
	var $theme = 'viendong';
	/**
	 @var $model
	 @brief Thông tin về model, được sử dụng trong trường hợp override thông tin của danh mục
	 */
	var $models = array(
		'Category'	=>	array(
			'plugin'	=>	'news',
			'name'		=>	'NewsCategory'
		),
		'Page'		=>	array(
			'plugin'	=>	'news',
			'name'		=>	'News'
		)
	);
	function beforeFilter() {
		parent::beforeFilter();
		
		foreach ($this->models as $key => $item) {
			App::import('Model', $item['plugin'].".".$item['name']);
			$this->loadModel($item['name']);
		}
		
		$this->set('models', $this->models);
		
		// save contact us information
		$this->configs = $this->{$this->models['Page']['name']}->loadConfig();
		$this->configs = $this->{$this->models['Page']['name']}->mergeConfig($this->configs, array(
			'configFolder'		=>	$this->models['Page']['plugin'],
			'names'				=> array($this->models['Page']['name'], 'RelatedImages', 'Category', 'Appearence'),
			'overrides'			=>	array(
				'EditablePage'	=>	$this->models['Page']['name']
			)
		));
		
		$this->set('configs', $this->configs);
		
	}
	
	function doSearch() {
		$keyword = '';
		//debug($this->data);
		if (isset($this->params['form']['q'])) {
			$keyword = urldecode($this->params['form']['q']);
		}
		//debug($this->params);
        $this->{$this->models['Page']['name']}->locale = Configure::read('Config.language');
		        
		$this->{$this->models['Page']['name']}->Behaviors->detach('Translate');
		$this->paginate[$this->models['Page']['name']] = array(
			'conditions'	=>	array(
				'OR'	=>	array(
					"{$this->models['Page']['name']}.title like '%{$keyword}%'",
					"{$this->models['Page']['name']}.description like '%{$keyword}%'",
					"{$this->models['Page']['name']}.content like '%{$keyword}%'",
				)
			),
			'fields'	=>	array('title', 'alias', 'image', 'description', 'Category.alias'),
            'joins'	=>	array(
				array(
					'table' => $this->News->hasAndBelongsToMany['Category']['joinTable'],
					'type' => 'INNER',
					'alias' => 'Middle',
					'conditions' => array(
						"Middle.page_id = News.id"
					)
				),
				array(
					'table' => $this->{$this->models['Category']['name']}->table,
					'type' => 'INNER',
					'alias' => 'Category',
					'conditions' => array(
						'Middle.category_id = Category.id'
					)
				),
			),
			'contain' => array(), 
			'limit' => 10
		);
		
		${$this->models['Page']['plugin']} = $this->paginate($this->models['Page']['name']);
		$this->set($this->models['Page']['plugin'], ${$this->models['Page']['plugin']});
		//debug(${$this->models['Page']['plugin']});    exit;
		$this->render('search_result');
    }
    
}
?>